"""
@Author: luoya
@Date: 2018/7/23
"""
import requests

from app.models.base import db
from app.models.book import Book


class Http(object):
    """
    获取数据
    """
    def __init__(self):
        self.books = []

    def get(self, url, return_json=True):
        r = requests.get(url)
        if r.status_code != 200:
            return {} if return_json else ''
        self.books = r.json()['books']
        return r.json() if return_json else r.text

    def save(self):
        for book in self.books:
            with db.auto_commit():
                model = Book()
                model.title = book['title']
                model.author = ','.join(book['author'])
                model.binding = book['binding']
                model.publisher = book['publisher']
                model.price = book['price']
                model.pages = book['pages']
                model.pubdate = book['pubdate']
                model.isbn = book['isbn']
                model.summary = book['summary']
                model.image = book['image']

                db.session.add(model)


